import datetime

from django.db import models

from sportsground.utils.baseModels import BaseModels, IntegerChoices


class UserCoupon(BaseModels):
    class Meta():
        db_table = 'user_coupon'
        verbose_name = '用户优惠券'
        verbose_name_plural = verbose_name

    class State(IntegerChoices):
        ToUse = 1, "待使用"
        Used = 2, "已使用"
        Expired = 3, "已过期"

    user = models.ForeignKey(to="User", on_delete=models.CASCADE, verbose_name="对应用户")
    coupon = models.ForeignKey(to="Venue.Coupon", null=True, on_delete=models.CASCADE, verbose_name="优惠券")
    state = models.IntegerField(choices=State.choices, default=State.ToUse, verbose_name="状态")
    order = models.ForeignKey(to="User.Order", null=True, on_delete=models.CASCADE, verbose_name="使用订单")

    @classmethod
    def create(cls,user,coupon):
        """ 创建 """
        coupon = cls(user=user,coupon=coupon,state=cls.State.ToUse)
        coupon.save()
        return coupon

    def Info(self):
        self.checkTimeout()
        return {
            "id": self.id,
            "state": self.state,
            "coupon": self.coupon.Info(),
            "getTime": self.createTime
        }

    def canPay(self,cost):
        return True

    def cost(self,money):
        """ 消费 """
        money -= self.coupon.derate
        self.state = self.State.Used
        self.save()
        return money

    def canUse(self,cost=None):
        """ 检查是否能使用 """
        if self.state != self.State.ToUse:
            return False
        if cost and cost < self.coupon.reach:
            return False
        now = datetime.datetime.now()
        if self.coupon.startTime < now < self.coupon.endTime:
            return True
        return False

    def checkTimeout(self):
        """ 检查过期状态 """
        if self.coupon.endTime <= datetime.datetime.now():
            self.state = self.State.Expired
            self.save()